package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.collections.Lists;

import com.example.tests3.SortedListOf;
import com.example.tests3.User;

public class UserPage extends InternalPage {

	@FindBy(name = "email")
	public WebElement emailField;
	
	@FindBy(name = "submit")
	public WebElement saveButton;
	
	@FindBy(xpath = "//img[@title=\"Remove\"]") 
	public WebElement deleteUser;
	
	@FindBy(id = "username")	
	  public WebElement userNameField;
    
    @FindBy(name = "password")
	  public WebElement passwordField;
    
    @FindBy(name = "password2")
	  public WebElement passwordFieldAgain;
    
    @FindBy(css="div#user-list table > tbody > tr")
      public List<WebElement> userRows;
    
    public UserPage createNewUser(User user) {
       userNameField.sendKeys(user.name);
       emailField.sendKeys(user.email);
       passwordField.sendKeys(user.password);
       passwordFieldAgain.sendKeys(user.password);
       saveButton.click();
      return MyPageFactory.getPage(driver, UserPage.class);  
    }
    
    public UserPage deleteUser(User user) {
    	for (WebElement row : userRows) {
        if (user.equals(convertRowToUser(row))){
        	row.findElement(By.xpath("./td[6]/a")).click();
        	wait_().until(alertIsPresent()).accept();
        break;	
        } 		
    }
       return MyPageFactory.getPage(driver, UserPage.class); 	
	}

	public SortedListOf<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row : userRows) {
		  users.add(convertRowToUser(row));	
  	}
		return new SortedListOf<User>(users);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User ()
		.withName(cells.get(1).getText())
		.withEmail(cells.get(2).getText())
		.withRole(cells.get(3).getText());
	}

	
}
